#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>
const QString SERVER_IP = "127.0.0.1";//ip地址
const quint16 SERVER_PORT = 9090;//端口号
//端口号本质上就是一个2字节的无符号的整数
//quint16本质就是一个unsigned short，对于short这个数据类型，C++标准上说short类型不少于2个字节


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //创建垂直布局管理器
    QVBoxLayout *vlayout=new QVBoxLayout(this);
    list_widget=new QListWidget(this);
    list_widget->resize(600,500);
    //添加控件
    vlayout->addWidget(list_widget);

    //创建水平布局
    QHBoxLayout *hlayout=new QHBoxLayout();
    line_edit=new QLineEdit();
    line_edit->setPlaceholderText("请输入要发送的信息");
    button=new QPushButton();
    button->setText("发送");
    //添加控件
    hlayout->addWidget(line_edit,4);
    hlayout->addWidget(button,1);

    vlayout->addLayout(hlayout);
    //显示
    this->setLayout(vlayout);

    //UDP
    //实例化socket对象
    socket=new QUdpSocket(this);
    //修改窗口标题
    this->setWindowTitle("客户端");

    //信号槽
    connect(button,&QPushButton::clicked,this,&Widget::handler_send);
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processResponse);
}

Widget::~Widget()
{
    delete ui;
}
//发送功能
void Widget::handler_send()
{
    //1、获取到输入框的内容
    const QString text=line_edit->text();
    //2、构造UDP请求数据包
    QNetworkDatagram requestDatagram(text.toUtf8(),
                                     QHostAddress(SERVER_IP),
                                     SERVER_PORT);
    //3、发送请求
    socket->writeDatagram(requestDatagram);
    //4、将发送的信息添加到列表框中
    list_widget->addItem("client: "+text);
    //5、将输入框清空
    line_edit->clear();
}

void Widget::processResponse()
{
    //获取到数据包
    const QNetworkDatagram responseDatagram=socket->receiveDatagram();
    //获取到有效载荷-有效数据
    QString response=responseDatagram.data();
    //将响应数据显示在界面上
    list_widget->addItem("server: "+response);
}

